<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,java集合容器," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="概述 ArrayList 是 List 接口下一个基于可扩展数组的实现类，它和它的兄弟类 Vector 有着一样的继承关系，也都能随机访问，但是不同的是不能保证线程安全。  这是关于 java 集合类源码的第三篇文章。往期文章：  java集合源码分析（一）：Collection 与 AbstractCollection  java集合源码分析（二）：List与AbstractLis">
<meta property="og:type" content="article">
<meta property="og:title" content="java集合源码分析（三）：ArrayList">
<meta property="og:url" content="http://blog.xiajibagao.top/2020/12/02/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%B8%89%EF%BC%89%EF%BC%9AArrayList/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="概述 ArrayList 是 List 接口下一个基于可扩展数组的实现类，它和它的兄弟类 Vector 有着一样的继承关系，也都能随机访问，但是不同的是不能保证线程安全。  这是关于 java 集合类源码的第三篇文章。往期文章：  java集合源码分析（一）：Collection 与 AbstractCollection  java集合源码分析（二）：List与AbstractLis">
<meta property="og:locale">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201201161347920.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201201194637410.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201202203515729.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201202134807874.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201202154625429.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201202202927612.png">
<meta property="article:published_time" content="2020-12-01T16:00:00.000Z">
<meta property="article:modified_time" content="2020-12-22T08:13:58.344Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="java">
<meta property="article:tag" content="java集合容器">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.xiajibagao.top/image-20201201161347920.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2020/12/02/java/集合类源码分析/java集合源码分析（三）：ArrayList/"/>





  <title>java集合源码分析（三）：ArrayList | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2020/12/02/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%B8%89%EF%BC%89%EF%BC%9AArrayList/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java集合源码分析（三）：ArrayList</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-02T00:00:00+08:00">
                2020-12-02
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java%E9%9B%86%E5%90%88%E5%AE%B9%E5%99%A8/" itemprop="url" rel="index">
                    <span itemprop="name">java集合容器</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  7.7k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概述">概述</h2>
<p>ArrayList 是 List 接口下一个基于可扩展数组的实现类，它和它的兄弟类 Vector 有着一样的继承关系，也都能随机访问，但是不同的是不能保证线程安全。</p>
<blockquote>
<p>这是关于 java 集合类源码的第三篇文章。往期文章：</p>
<ol type="1">
<li><a href="https://blog.xiajibagao.top/2020/11/25/java/集合类源码分析/java集合源码分析（一）：Collection与AbstractCollection/">java集合源码分析（一）：Collection 与 AbstractCollection</a><br>
</li>
<li><a href="https://blog.xiajibagao.top/2020/11/27/java/集合类源码分析/java集合源码分析（二）：List与AbstractList/">java集合源码分析（二）：List与AbstractList</a></li>
</ol>
</blockquote>
<h2 id="一-arraylist-的类关系">一、ArrayList 的类关系</h2>
<figure>
<img src="http://img.xiajibagao.top/image-20201201161347920.png" alt="image-20201201161347920"><figcaption aria-hidden="true">image-20201201161347920</figcaption>
</figure>
<p>ArrayList 实现了三个接口，继承了一个抽象类，其中 Serializable ，Cloneable 与 RandomAccess 接口都是用于标记的空接口，他的主要抽象方法来自于 List，一些实现来自于 AbstractList。</p>
<h3 id="1abstractlist-与-list">1.AbstractList 与 List</h3>
<p>ArrayList 实现了 List 接口，是 List 接口的实现类之一，他通过继承抽象类 AbstractList 获得的大部分方法的实现。</p>
<p>比较特别的是，理论上父类 AbstractList 已经实现类 AbstractList 接口，那么理论上 ArrayList 就已经可以通过父类获取 List 中的抽象方法了，不必再去实现 List 接口。</p>
<p>网上关于这个问题的答案众说纷纭，有说是为了通过共同的接口便于实现 JDK 代理，也有说是为了代码规范性与可读性的，在 Stack Overflow 上 <a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/2165204/why-does-linkedhashsete-extend-hashsete-and-implement-sete">Why does LinkedHashSet extend HashSet and implement Set</a> 一个据说问过原作者的老哥给出了一个 <code>it was a mistake</code> 的回答，但是这似乎不足以解释为什么几乎所有的容器类都有类似的行为。事实到底是怎么回事，也许只有真正的原作者知道了。</p>
<h3 id="2randomaccess">2.RandomAccess</h3>
<p>RandomAccess 是一个标记性的接口，实现了此接口的集合是允许被随机访问的。</p>
<p>根据 JavaDoc 的说法，如果一个类实现了此接口，那么：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>, n=list.size(); i &lt; n; i++)</span><br><span class="line">    list.get(i);</span><br></pre></td></tr></table></figure>
<p>要快于</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (Iterator i=list.iterator(); i.hasNext(); )</span><br><span class="line">    i.next();</span><br></pre></td></tr></table></figure>
<p>随机访问其实就是根据下标访问，以 LinkedList 和 ArrayList 为例，LinkedList 底层实现是链表，随机访问需要遍历链表，复杂度为 O(n)，而 ArrayList 底层实现为数组，随机访问直接通过下标去寻址就行了，复杂度是O(1)。</p>
<p>当我们需要指定迭代的算法的时候，可以通过实现类是否实现了 RandomAccess 接口来选择对应的迭代方式。在一些方法操作集合的方法里（比如 AbstractList 中的 subList），也根据这点做了一些处理。</p>
<h3 id="3cloneable">3.Cloneable</h3>
<p>Cloneable 接口表示它的实现类是可以被拷贝的，根据 JavaDoc 的说法：</p>
<blockquote>
<p>一个类实现Cloneable接口，以表明该通过Object.clone()方法为该类的实例进行逐域复制是合法的。</p>
<p>在未实现Cloneable接口的实例上调用Object的clone方法会导致抛出CloneNotSupportedException异常。</p>
<p>按照约定，实现此接口的类应使用公共方法重写Object.clone()。</p>
</blockquote>
<p>简单的说，如果一个类想要使用<code>Object.clone()</code>方法以实现对象的拷贝，那么这个类需要实现 Cloneable 接口并且重写 <code>Object.clone()</code>方法。值得一提的是，<code>Object.clone()</code>默认提供的拷贝是浅拷贝，浅拷贝实际上没有拷贝并且创建一个新的实例，通过浅拷贝获得的对象变量其实还是指针，指向的还是原来那个内存地址。深拷贝的方法需要我们自己提供。</p>
<h3 id="4serializable">4.Serializable</h3>
<p>Serializable 接口也是一个标记性接口，他表明实现类是可以被序列化与反序列化的。</p>
<p>这里提一下序列化的概念。</p>
<blockquote>
<p>序列化是指把一个 Java 对象变成二进制内容的过程，本质上就是把对象转为一个 byte[] 数组，反序列化同理。</p>
<p>当一个 java 对象序列化以后，就可以得到的 byte[] 保存到文件中，或者把 byte[] 通过网络传输到远程，这样就相当于把 Java 对象存储到文件或者通过网络传输出去了。</p>
</blockquote>
<p>值得一提的是，针对一些不希望被存储到文件，或者以字节流的形式被传输的私密信息，java 提供了 transient 关键字，被其标记的属性不会被序列化。比如在 AbstractList 里，之前提到的并发修改检查中用于记录结构性操作次数的变量 <code>modCount</code>，还有下面要介绍到的 ArrayList 的底层数组 elementData 就是被 transient 关键字修饰的。</p>
<p>更多的内容可以参考大佬的博文：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/lanxuezaipiao/p/3369962.html">Java transient关键字使用小记</a></p>
<h2 id="二-成员变量">二、成员变量</h2>
<p>在 ArrayList 中，一共有四个常量，两个成员变量：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">8683452581122892189L</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 默认初始容量</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DEFAULT_CAPACITY = <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 用于空实例的共享空数组实例</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Object[] EMPTY_ELEMENTDATA = &#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 共享的空数组实例，用于默认大小的空实例。我们将此与EMPTY_ELEMENTDATA区别开来，以了解添加第一个元素时要扩容数组到多大。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = &#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 存储ArrayList的元素的数组缓冲区。 ArrayList的容量是此数组缓冲区的长度。添加第一个元素时，任何符合</span></span><br><span class="line"><span class="comment"> * elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 的空ArrayList都将扩展为DEFAULT_CAPACITY。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">transient</span> Object[] elementData;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ArrayList的大小（它包含的元素数）</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> size;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 要分配的最大数组大小</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> MAX_ARRAY_SIZE = Integer.MAX_VALUE - <span class="number">8</span>;</span><br></pre></td></tr></table></figure>
<p>我们来一个一个的解释他们的作用。</p>
<h3 id="1serialversionuid">1.serialVersionUID</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">8683452581122892189L</span>;</span><br></pre></td></tr></table></figure>
<p>用于序列化检测的 UUID，我们可以简单的理解他的作用：</p>
<blockquote>
<p>当序列化以后，serialVersionUID 会被一起写入文件，当反序列化的时候，JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较，如果相同就认为是一致的，可以进行反序列化，否则就会出现序列化版本不一致的异常，即是InvalidCastException。</p>
</blockquote>
<p>更多内容仍然可以参考大佬的博文：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/duanxz/p/3511695.html">java类中serialversionuid 作用 是什么?举个例子说明</a></p>
<h3 id="2default_capacity">2.DEFAULT_CAPACITY</h3>
<p>默认容量，如果实例化的时候没有在构造方法里指定初始容量大小，第一个扩容就会根据这个值扩容。</p>
<h3 id="3empty_elementdata">3.EMPTY_ELEMENTDATA</h3>
<p>一个空数组，<strong>当调用构造方法的时候指定容量为0</strong>，或者其他什么操作会导致集合内数组长度变为0的时候，就会直接把空数组赋给集合实际用于存放数据的数组 <code>elementData</code>。</p>
<h3 id="4defaultcapacity_empty_elementdata">4.DEFAULTCAPACITY_EMPTY_ELEMENTDATA</h3>
<p>也是一个空数组，不同于 <code>EMPTY_ELEMENTDATA</code> 是指定了容量为0的时候会被赋给elementData，而<code>DEFAULTCAPACITY_EMPTY_ELEMENTDATA</code>是在不指定容量的时候才会被赋给 <code>elementData</code>，而且添加第一个元素的时候就会被扩容。</p>
<p><code>DEFAULTCAPACITY_EMPTY_ELEMENTDATA</code>和 <code>EMPTY_ELEMENTDATA</code>都不影响实际后续往里头添加元素，两者主要表示一个逻辑上的区别：前者表示集合目前为空，但是以后可能会添加元素，而后者表示这个集合一开始就没打算存任何东西，是个容量为0的空集合。</p>
<h3 id="5elementdata">5.elementData</h3>
<p>实际存放数据的数组，当扩容或者其他什么操作的时候，会先把数据拷贝到新数组，然后让这个变量指向新数组。</p>
<h3 id="6size">6.size</h3>
<p>集合中的元素数量（注意不是数组长度）。</p>
<h3 id="7max_array_size">7.MAX_ARRAY_SIZE</h3>
<p>允许的最大数组长度，之所以等于 <code>Integer.MAX_VALUE - 8</code>，是为了防止在一些虚拟机中数组头会被用于保持一些其他信息。</p>
<h2 id="三-构造方法">三、构造方法</h2>
<p>ArrayList 中提供了三个构造方法：</p>
<ul>
<li><code>ArrayList()</code></li>
<li><code>ArrayList(int initialCapacity)</code></li>
<li><code>ArrayList(Collection&lt;? extends E&gt; c)</code></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1.构造一个空集合</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ArrayList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2.构造一个具有指定初始容量的空集合</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ArrayList</span><span class="params">(<span class="keyword">int</span> initialCapacity)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 判断指定的初始容量是否大于0</span></span><br><span class="line">    <span class="keyword">if</span> (initialCapacity &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// 若大于0，则直接指定elementData数组的长度</span></span><br><span class="line">        <span class="keyword">this</span>.elementData = <span class="keyword">new</span> Object[initialCapacity];</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (initialCapacity == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// 若等于0，将EMPTY_ELEMENTDATA赋给elementData</span></span><br><span class="line">        <span class="keyword">this</span>.elementData = EMPTY_ELEMENTDATA;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 小于0，抛异常</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Illegal Capacity: &quot;</span> + initialCapacity);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 3.构造一个包含指定集合所有元素的集合</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ArrayList</span><span class="params">(Collection&lt;? extends E&gt; c)</span> </span>&#123;</span><br><span class="line">    elementData = c.toArray();</span><br><span class="line">    <span class="comment">// 判断传入的集合是否为空集合</span></span><br><span class="line">    <span class="keyword">if</span> ((size = elementData.length) != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// 确认转为的集合底层实现是否也是Objcet数组</span></span><br><span class="line">        <span class="keyword">if</span> (elementData.getClass() != Object[].class)</span><br><span class="line">            elementData = Arrays.copyOf(elementData, size, Object[].class);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 如果是空集合，将EMPTY_ELEMENTDATA赋给elementData</span></span><br><span class="line">        <span class="keyword">this</span>.elementData = EMPTY_ELEMENTDATA;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们一般使用比较多的是第一种，有时候会用第三种，实际上，如果我们可以估计到实际会添加多少元素，就可以使用第二种构造器指定容量，避免扩容带来的消耗。</p>
<h2 id="四-扩容缩容">四、扩容缩容</h2>
<p>ArrayList 的可扩展性是它最重要的特性之一，在开始了解其他方法前，我们需要先了解一下 ArrayList 是如何实现扩容和缩容的。</p>
<h3 id="0systemarraycopy">0.System.arraycopy()</h3>
<p>在这之前，我们需要理解一下扩容缩容所依赖的核心方法 <code>System.arraycopy()</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 从一个源数组复制元素到另一个数组，如果该数组指定位置已经有元素，就使用复制过来的元素替换它</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> src 要复制的源数组</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> srcPos 要从源数组哪个下标开始复制</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> dest 要被移入元素的数组</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> destPos  要从被移入元素数组哪个下标开始替换</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> length 复制元素的个数</span></span><br><span class="line"><span class="comment"> */</span>   </span><br><span class="line">arraycopy(Object src,  <span class="keyword">int</span>  srcPos,</span><br><span class="line">          Object dest, <span class="keyword">int</span> destPos,</span><br><span class="line">          <span class="keyword">int</span> length)</span><br></pre></td></tr></table></figure>
<p>我们举个例子，假如我们现在有 <code>arr1 = &#123;1,2,3,4,5&#125;</code>和 <code>arr2 = &#123;6,7,8,9,10&#125;</code>，现在我们使用 <code>arraycopy(arr1, 0, arr2, 0, 2)</code>，则意为：</p>
<p>使用从 arr1 索引为 0 的元素开始，复制 2 个元素，然后把这两个元素从 arr2 数组中索引为 0 的地方开始替换原本的元素，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span>[] arr1 = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>&#125;;</span><br><span class="line"><span class="keyword">int</span>[] arr2 = &#123;<span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>&#125;;</span><br><span class="line">System.arraycopy(arr1, <span class="number">0</span>, arr2, <span class="number">0</span>, <span class="number">2</span>);</span><br><span class="line"><span class="comment">// arr2 = &#123;1，2，8，9，10&#125;</span></span><br></pre></td></tr></table></figure>
<h3 id="1扩容">1.扩容</h3>
<p>虽然在 AbstractCollection 抽象类中已经有了简单的扩容方法 <code>finishToArray()</code>，但是 ArrayList 没有继续使用它，而是自己重新实现了扩容的过程。ArrayList 的扩容过程一般发生在新增元素上。</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201201194637410.png" alt="会引起ArrayList扩容的方法"><figcaption aria-hidden="true">会引起ArrayList扩容的方法</figcaption>
</figure>
<p>我们以 <code>add()</code> 方法为例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 判断新元素加入后，集合是否需要扩容</span></span><br><span class="line">    ensureCapacityInternal(size + <span class="number">1</span>);</span><br><span class="line">    elementData[size++] = e;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>（1）检查是否初次扩容</strong></p>
<p>我们知道，在使用构造函数构建集合的时候，如果未指定初始容量，则内部数组 <code>elementData</code> 会被赋上默认空数组 <code>DEFAULTCAPACITY_EMPTY_ELEMENTDATA</code>。</p>
<p>因此，当我们调用 <code>add()</code>时，会先调用 <code>ensureCapacityInternal()</code>方法判断<code>elementData</code> 是否还是<code>DEFAULTCAPACITY_EMPTY_ELEMENTDATA</code>，<strong>如果是，说明创建的时候没有指定初始容量，而且没有被扩容过</strong>，因此要保证集合被扩容到10或者更大的容量：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">ensureCapacityInternal</span><span class="params">(<span class="keyword">int</span> minCapacity)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 判断是否还是初始状态</span></span><br><span class="line">    <span class="keyword">if</span> (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) &#123;</span><br><span class="line">        <span class="comment">// 扩容到默认容量（10）或更大</span></span><br><span class="line">        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    ensureExplicitCapacity(minCapacity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>（2）检查是否需要扩容</strong></p>
<p>当决定好了第一次扩容的大小，或者<code>elementData</code>被扩容过最少一次以后，就会进入到扩容的准备过程<code>ensureExplicitCapacity()</code>，在这个方法中，<strong>将会增加操作计数器<code>modCount</code>，并且保证新容量要比当前数组长度大</strong>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">ensureExplicitCapacity</span><span class="params">(<span class="keyword">int</span> minCapacity)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 扩容也是结构性操作，modCount+1</span></span><br><span class="line">    modCount++;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 判断最小所需容量是否大于当前底层数组长度</span></span><br><span class="line">    <span class="keyword">if</span> (minCapacity - elementData.length &gt; <span class="number">0</span>)</span><br><span class="line">        grow(minCapacity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>（3）扩容</strong></p>
<p>最后进入真正的扩容方法 <code>grow()</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 扩容</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">grow</span><span class="params">(<span class="keyword">int</span> minCapacity)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 旧容量为数组当前长度</span></span><br><span class="line">    <span class="keyword">int</span> oldCapacity = elementData.length;</span><br><span class="line">    <span class="comment">// 新容量为旧容量的1.5倍</span></span><br><span class="line">    <span class="keyword">int</span> newCapacity = oldCapacity + (oldCapacity &gt;&gt; <span class="number">1</span>);</span><br><span class="line">    <span class="comment">// 如果新容量小于最小所需容量（size + 1），就以最小所需容量作为新容量</span></span><br><span class="line">    <span class="keyword">if</span> (newCapacity - minCapacity &lt; <span class="number">0</span>)</span><br><span class="line">        newCapacity = minCapacity;</span><br><span class="line">    <span class="comment">// 如果新容量大于允许的最大容量，就再判断能否再继续扩容</span></span><br><span class="line">    <span class="keyword">if</span> (newCapacity - MAX_ARRAY_SIZE &gt; <span class="number">0</span>)</span><br><span class="line">        newCapacity = hugeCapacity(minCapacity);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 扩容完毕，将旧数组的数据拷贝到新数组上</span></span><br><span class="line">    elementData = Arrays.copyOf(elementData, newCapacity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里可能有人会有疑问，为什么<code>oldCapacity</code>要等于<code>elementData.length</code>而不可以是 <code>size()</code>呢？</p>
<p>因为在 ArrayList，既有需要彻底移除元素并新建数组的真删除，也有只是对应下标元素设置为 null 的假删除，<strong><code>size()</code>实际计算的是有元素个数</strong>，因此这里需要使用<code>elementData.length</code>来了解数组的真实长度。</p>
<p>回到扩容，由于 <code>MAX_ARRAY_SIZE</code>已经是理论上允许的最大扩容大小了，如果新容量比<code>MAX_ARRAY_SIZE</code>还大，那么就涉及到一个临界扩容大小的问题，<code>hugeCapacity()</code>方法被用于决定<strong>最终允许的容量大小</strong>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">hugeCapacity</span><span class="params">(<span class="keyword">int</span> minCapacity)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 是否发生溢出</span></span><br><span class="line">    <span class="keyword">if</span> (minCapacity &lt; <span class="number">0</span>) <span class="comment">// overflow</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> OutOfMemoryError</span><br><span class="line">        (<span class="string">&quot;Required array size too large&quot;</span>);</span><br><span class="line">    <span class="comment">// 判断最终大小是MAX_ARRAY_SIZE还是Integer.MAX_VALUE</span></span><br><span class="line">    <span class="keyword">return</span> (minCapacity &gt; MAX_ARRAY_SIZE) ?</span><br><span class="line">        Integer.MAX_VALUE :</span><br><span class="line">    MAX_ARRAY_SIZE;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ArrayList 的 <code>hugeCapacity()</code>与 <code>AbstractCollection</code>抽象类中的 <code>hugeCapacity()</code>是完全一样的，当 <code>minCapacity &gt; MAX_ARRAY_SIZE</code>的情况成立的时候，说明现在的当前元素个数<code>size</code>容量已经等于 <code>MAX_ARRAY_SIZE</code>，数组已经极大了，这个时候再进行拷贝操作会非常消耗性能，因此最后一次扩容会直接扩到 <code>Integer.MAX_VALUE</code>，如果再大就只能溢出了。</p>
<p>以下是扩容的流程图：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201202203515729.png" alt="ArrayList 的扩容流程"><figcaption aria-hidden="true">ArrayList 的扩容流程</figcaption>
</figure>
<h3 id="2缩容">2.缩容</h3>
<p>除了扩容，ArrayList 还提供了缩容的方法 <code>trimToSize()</code>，但是这个方法不被任何其他内部方法调用，只能由程序猿自己去调用，主动让 ArrayList 瘦身，因此在日常使用中并不是很常见。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">trimToSize</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 结构性操作，modCount+1</span></span><br><span class="line">    modCount++;</span><br><span class="line">    <span class="comment">// 判断当前元素个数是否小于当前底层数组的长度</span></span><br><span class="line">    <span class="keyword">if</span> (size &lt; elementData.length) &#123;</span><br><span class="line">        <span class="comment">// 如果长度为0，就变为EMPTY_ELEMENTDATA空数组</span></span><br><span class="line">        elementData = (size == <span class="number">0</span>)</span><br><span class="line">            ? EMPTY_ELEMENTDATA</span><br><span class="line">            <span class="comment">// 否则就把容量缩小为当前的元素个数</span></span><br><span class="line">            : Arrays.copyOf(elementData, size);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3测试">3.测试</h3>
<p>我们可以借助反射，来看看 ArrayList 的扩容和缩容过程：</p>
<p>先写一个通过反射获取 elementData 的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 通过反射获取值</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">getEleSize</span><span class="params">(List&lt;?&gt; list)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line"></span><br><span class="line">        Field ele = list.getClass().getDeclaredField(<span class="string">&quot;elementData&quot;</span>);</span><br><span class="line">        ele.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">        Object[] arr = (Object[]) ele.get(list);</span><br><span class="line">        System.out.println(<span class="string">&quot;当前elementData数组的长度：&quot;</span> + arr.length);</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">catch</span> (NoSuchFieldException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后实验看看：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 第一次扩容</span></span><br><span class="line">    ArrayList&lt;String&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    getEleSize(list); <span class="comment">// 当前elementData数组的长度：0</span></span><br><span class="line">    list.add(<span class="string">&quot;aaa&quot;</span>);</span><br><span class="line">    getEleSize(list); <span class="comment">// 当前elementData数组的长度：10</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 指定初始容量为0的集合，进行第一次扩容</span></span><br><span class="line">    ArrayList&lt;String&gt; emptyList = <span class="keyword">new</span> ArrayList&lt;&gt;(<span class="number">0</span>);</span><br><span class="line">    getEleSize(emptyList); <span class="comment">// 当前elementData数组的长度：0</span></span><br><span class="line">    emptyList.add(<span class="string">&quot;aaa&quot;</span>);</span><br><span class="line">    getEleSize(emptyList); <span class="comment">// 当前elementData数组的长度：1</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 扩容1.5倍</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">        list.add(<span class="string">&quot;aaa&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    getEleSize(list); <span class="comment">// 当前elementData数组的长度：15</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 缩容</span></span><br><span class="line">    list.trimToSize();</span><br><span class="line">    getEleSize(list);<span class="comment">// 当前elementData数组的长度：11</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="五-添加-获取">五、添加 / 获取</h2>
<h3 id="1add">1.add</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 如果需要就先扩容</span></span><br><span class="line">    ensureCapacityInternal(size + <span class="number">1</span>);</span><br><span class="line">    <span class="comment">// 添加到当前位置的下一位</span></span><br><span class="line">    elementData[size++] = e;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> index, E element)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 若 index &gt; size || index &lt; 0 则抛 IndexOutOfBoundsException 异常</span></span><br><span class="line">    rangeCheckForAdd(index);</span><br><span class="line">    <span class="comment">// 如果需要就先扩容</span></span><br><span class="line">    ensureCapacityInternal(size + <span class="number">1</span>);</span><br><span class="line">    <span class="comment">// 把原本 index 下标以后的元素集体后移一位,为新插入的数组腾位置</span></span><br><span class="line">    System.arraycopy(elementData, index, elementData, index + <span class="number">1</span>,</span><br><span class="line">                     size - index);</span><br><span class="line">    elementData[index] = element;</span><br><span class="line">    size++;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>添加的原理比较简单，实际上就是如果不指定下标就插到数组尾部，否则就先创建一个新数组，然后把旧数组的数据移动到新数组，并且在这个过程中提前在新数组上留好要插入的元素的空位，最后再把元素插入数组。后面的增删操作基本都是这个原理。</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201202134807874.png" alt="ArrayList 的新增"><figcaption aria-hidden="true">ArrayList 的新增</figcaption>
</figure>
<h3 id="2addall">2.addAll</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">addAll</span><span class="params">(Collection&lt;? extends E&gt; c)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 将新集合的数组取出</span></span><br><span class="line">    Object[] a = c.toArray();</span><br><span class="line">    <span class="keyword">int</span> numNew = a.length;</span><br><span class="line">    <span class="comment">// 如有必要就扩容</span></span><br><span class="line">    ensureCapacityInternal(size + numNew);</span><br><span class="line">    <span class="comment">// 将新数组拼接到原数组的尾部</span></span><br><span class="line">    System.arraycopy(a, <span class="number">0</span>, elementData, size, numNew);</span><br><span class="line">    size += numNew;</span><br><span class="line">    <span class="keyword">return</span> numNew != <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">addAll</span><span class="params">(<span class="keyword">int</span> index, Collection&lt;? extends E&gt; c)</span> </span>&#123;</span><br><span class="line">    rangeCheckForAdd(index);</span><br><span class="line"></span><br><span class="line">    Object[] a = c.toArray();</span><br><span class="line">    <span class="keyword">int</span> numNew = a.length;</span><br><span class="line">    <span class="comment">// 先扩容</span></span><br><span class="line">    ensureCapacityInternal(size + numNew);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 判断是否需要移动原数组</span></span><br><span class="line">    <span class="keyword">int</span> numMoved = size - index;</span><br><span class="line">    <span class="keyword">if</span> (numMoved &gt; <span class="number">0</span>)</span><br><span class="line">        <span class="comment">// 则将原本 index 下标以后的元素移到 index + numNew 的位置</span></span><br><span class="line">        System.arraycopy(elementData, index, elementData, index + numNew,</span><br><span class="line">                         numMoved);</span><br><span class="line"></span><br><span class="line">    System.arraycopy(a, <span class="number">0</span>, elementData, index, numNew);</span><br><span class="line">    size += numNew;</span><br><span class="line">    <span class="keyword">return</span> numNew != <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3get">3.get</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">get</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    rangeCheck(index);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> elementData(index);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 根据下标从数组中取值，被使用在get(),set(),remove()等方法中</span></span><br><span class="line"><span class="function">E <span class="title">elementData</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (E) elementData[index];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="六-删除-修改">六、删除 / 修改</h2>
<h3 id="1remove">1.remove</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">remove</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 若 index &gt;= size 会抛出 IndexOutOfBoundsException 异常</span></span><br><span class="line">    rangeCheck(index);</span><br><span class="line"></span><br><span class="line">    modCount++;</span><br><span class="line">    E oldValue = elementData(index);</span><br><span class="line">	</span><br><span class="line">    <span class="comment">// 判断是否需要移动数组</span></span><br><span class="line">    <span class="keyword">int</span> numMoved = size - index - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">if</span> (numMoved &gt; <span class="number">0</span>)</span><br><span class="line">        System.arraycopy(elementData, index+<span class="number">1</span>, elementData, index,</span><br><span class="line">                         numMoved);</span><br><span class="line">    <span class="comment">// 把元素尾部位置设置为null，便于下一次插入</span></span><br><span class="line">    elementData[--size] = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> oldValue;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">remove</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 如果要删除的元素是null</span></span><br><span class="line">    <span class="keyword">if</span> (o == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> index = <span class="number">0</span>; index &lt; size; index++)</span><br><span class="line">            <span class="comment">// 移除第一位为null的元素</span></span><br><span class="line">            <span class="keyword">if</span> (elementData[index] == <span class="keyword">null</span>) &#123;</span><br><span class="line">                fastRemove(index);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 如果要删除的元素不为null</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> index = <span class="number">0</span>; index &lt; size; index++)</span><br><span class="line">            <span class="keyword">if</span> (o.equals(elementData[index])) &#123;</span><br><span class="line">                fastRemove(index);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里有用到一个<code>fastRemove()</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// fast 的地方在于：跳过边界检查，并且不返回删除的值</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">fastRemove</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    modCount++;</span><br><span class="line">    <span class="keyword">int</span> numMoved = size - index - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">if</span> (numMoved &gt; <span class="number">0</span>)</span><br><span class="line">        System.arraycopy(elementData, index+<span class="number">1</span>, elementData, index,</span><br><span class="line">                         numMoved);</span><br><span class="line">    elementData[--size] = <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>比较有趣的地方在于，<code>remove()</code>的时候检查的是<code>index &gt;= size</code>，而 <code>add()</code>的时候检查的是 <code>index &gt; size || index &lt; 0</code>，可见添加的时候还要看看 index 是否小于0。</p>
<p>原因在于 <code>add()</code>在校验完以后，立刻就会调用<code>System.arraycopy()</code>，由于这是个 native 方法，所以出错不会抛异常；而 <code>remve()</code> 调用完后，会先使用 <code>elementData(index)</code>取值，这时如果 <code>index&lt;0</code> 会直接抛异常。</p>
<h3 id="2clear">2.clear</h3>
<p>比较需要注意的是，相比起<code>remove()</code>方法，<code>clear()</code>只是把数组的每一位都设置为null，<code>elementData</code>的长度是没有改变的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clear</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    modCount++;</span><br><span class="line">	<span class="comment">// 把数组每一位都设置为null</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; size; i++)</span><br><span class="line">        elementData[i] = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    size = <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3removeall-retainall">3.removeAll / retainAll</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">removeAll</span><span class="params">(Collection&lt;?&gt; c)</span> </span>&#123;</span><br><span class="line">    Objects.requireNonNull(c);</span><br><span class="line">    <span class="keyword">return</span> batchRemove(c, <span class="keyword">false</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">retainAll</span><span class="params">(Collection&lt;?&gt; c)</span> </span>&#123;</span><br><span class="line">    Objects.requireNonNull(c);</span><br><span class="line">    <span class="keyword">return</span> batchRemove(c, <span class="keyword">true</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这两个方法都依赖于 <code>batchRemove()</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">batchRemove</span><span class="params">(Collection&lt;?&gt; c, <span class="keyword">boolean</span> complement)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> Object[] elementData = <span class="keyword">this</span>.elementData;</span><br><span class="line">    <span class="keyword">int</span> r = <span class="number">0</span>, w = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">boolean</span> modified = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 1.遍历本集合</span></span><br><span class="line">        <span class="keyword">for</span> (; r &lt; size; r++)</span><br><span class="line">            <span class="comment">// 如果新增集合存在与本集合存在相同的元素，有两种情况</span></span><br><span class="line">            <span class="comment">// 1.removeAll，complement=false：直接跳过该元素</span></span><br><span class="line">            <span class="comment">// 2.retainAll，complement=true：把新元素插入原集合头部</span></span><br><span class="line">            <span class="keyword">if</span> (c.contains(elementData[r]) == complement)</span><br><span class="line">                elementData[w++] = elementData[r];</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">// 2.如果上述操作中发生异常，则判断是否已经完成本集合的遍历</span></span><br><span class="line">        <span class="keyword">if</span> (r != size) &#123;</span><br><span class="line">            System.arraycopy(elementData, r,</span><br><span class="line">                             elementData, w,</span><br><span class="line">                             size - r);</span><br><span class="line">            w += size - r;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (w != size) &#123;</span><br><span class="line">            <span class="comment">// 3.将数组剩下的位置都改为null</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = w; i &lt; size; i++)</span><br><span class="line">                elementData[i] = <span class="keyword">null</span>;</span><br><span class="line">            modCount += size - w;</span><br><span class="line">            size = w;</span><br><span class="line">            modified = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> modified;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述这三个过程可能有点难一点理解，我们假设这是 <code>retailAll()</code>，因此 <code>complement=true</code>，执行流程是这样的：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201202154625429.png" alt="batchRemove 的执行逻辑"><figcaption aria-hidden="true">batchRemove 的执行逻辑</figcaption>
</figure>
<p>同理，如果是<code>removeAll()</code>，那么 w 就会始终为0，最后就会把 elementData 的所有位置都设置为 null。</p>
<p>也就是说，在遍历过程中如果不发生异常，就会跳过第二步，直接进入第三步。</p>
<p>当然，这是没有发生异常的情况，因此遍历完成后 <code>r = size</code>，那么如果遍历到 <code>r = 2</code>，也就是进入 if 分支后，程序发生了异常，尚未完成遍历就进入了 finallly 块，就会先进入第二步，也就是下面的流程：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201202202927612.png" alt="batchRemove 发生异常时的执行逻辑"><figcaption aria-hidden="true">batchRemove 发生异常时的执行逻辑</figcaption>
</figure>
<p>最终数组会变为 {C，C，D，null} ，只有最后一个 D 被删除。</p>
<h3 id="4removeif">4.removeIf</h3>
<p>这个是 JDK8 以后的新增方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">removeIf</span><span class="params">(Predicate&lt;? <span class="keyword">super</span> E&gt; filter)</span> </span>&#123;</span><br><span class="line">    Objects.requireNonNull(filter);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">int</span> removeCount = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">final</span> BitSet removeSet = <span class="keyword">new</span> BitSet(size);</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> size = <span class="keyword">this</span>.size;</span><br><span class="line">    <span class="comment">// 遍历集合，同时做并发修改检查</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; modCount == expectedModCount &amp;&amp; i &lt; size; i++) &#123;</span><br><span class="line">        <span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span></span><br><span class="line">        <span class="keyword">final</span> E element = (E) elementData[i];</span><br><span class="line">        <span class="comment">// 使用 lambda 表达式传入的匿名方法校验元素</span></span><br><span class="line">        <span class="keyword">if</span> (filter.test(element)) &#123;</span><br><span class="line">            removeSet.set(i);</span><br><span class="line">            removeCount++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 并发修改检测</span></span><br><span class="line">    <span class="keyword">if</span> (modCount != expectedModCount) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 是否有有需要删除的元素</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">boolean</span> anyToRemove = removeCount &gt; <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (anyToRemove) &#123;</span><br><span class="line">        <span class="comment">// 新容量为旧容量-删除元素数量</span></span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> newSize = size - removeCount;</span><br><span class="line">        <span class="comment">// 把被删除的元素留下的空位“补齐”</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>, j=<span class="number">0</span>; (i &lt; size) &amp;&amp; (j &lt; newSize); i++, j++) &#123;</span><br><span class="line">            i = removeSet.nextClearBit(i);</span><br><span class="line">            elementData[j] = elementData[i];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 将删除的位置设置为null</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> k=newSize; k &lt; size; k++) &#123;</span><br><span class="line">            elementData[k] = <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.size = newSize;</span><br><span class="line">        <span class="keyword">if</span> (modCount != expectedModCount) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">        &#125;</span><br><span class="line">        modCount++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> anyToRemove;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="5set">5.set</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">set</span><span class="params">(<span class="keyword">int</span> index, E element)</span> </span>&#123;</span><br><span class="line">    rangeCheck(index);</span><br><span class="line"></span><br><span class="line">    E oldValue = elementData(index);</span><br><span class="line">    elementData[index] = element;</span><br><span class="line">    <span class="keyword">return</span> oldValue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="6replaceall">6.replaceAll</h3>
<p>这也是一个 JDK8 新增的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">replaceAll</span><span class="params">(UnaryOperator&lt;E&gt; operator)</span> </span>&#123;</span><br><span class="line">    Objects.requireNonNull(operator);</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> size = <span class="keyword">this</span>.size;</span><br><span class="line">    <span class="comment">// 遍历，并使用lambda表达式传入的匿名函数处理每一个元素</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; modCount == expectedModCount &amp;&amp; i &lt; size; i++) &#123;</span><br><span class="line">        elementData[i] = operator.apply((E) elementData[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (modCount != expectedModCount) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">    modCount++;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="七-迭代">七、迭代</h2>
<h3 id="1iterator-listiterator">1.iterator / listIterator</h3>
<p>ArrayList 重新实现了自己的迭代器，而不是继续使用 AbstractList 提供的迭代器。</p>
<p>和 AbstracList 一样，ArrayList 实现的迭代器内部类仍然是基础迭代器 Itr 和加强的迭代器 ListItr，他和 AbstractList 中的两个同名内部类基本一样，但是针对 ArrayList 的特性对方法做了一些调整：比如一些地方取消了对内部方法的调用，直接对 elementData 下标进行操作等。</p>
<p>这一块可以参考上篇文章，或者看看源码，这里就不赘述了。</p>
<h3 id="2foreach">2.forEach</h3>
<p>这是一个针对 Collection 的父接口 Iterable 接口中 forEach 方法的重写。在 ArrayList 的实现是这样的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">forEach</span><span class="params">(Consumer&lt;? <span class="keyword">super</span> E&gt; action)</span> </span>&#123;</span><br><span class="line">    Objects.requireNonNull(action);</span><br><span class="line">    <span class="comment">// 获取 modCount</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">    <span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span></span><br><span class="line">    <span class="keyword">final</span> E[] elementData = (E[]) <span class="keyword">this</span>.elementData;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> size = <span class="keyword">this</span>.size;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; modCount == expectedModCount &amp;&amp; i &lt; size; i++) &#123;</span><br><span class="line">        <span class="comment">// 遍历元素并调用lambda表达式处理元素</span></span><br><span class="line">        action.accept(elementData[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 遍历结束后才进行并发修改检测</span></span><br><span class="line">    <span class="keyword">if</span> (modCount != expectedModCount) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3迭代删除存在的问题">3.迭代删除存在的问题</h3>
<p>到目前为止，我们知道有三种迭代方式：</p>
<ul>
<li>使用 <code>iterator()</code>或<code>listIterator()</code>获取迭代器；</li>
<li><code>forEach()</code>；</li>
<li>for 循环。</li>
</ul>
<p>如果我们在循环中删除集合的节点，只有迭代器的方式可以正常删除，其他都会出问题。</p>
<p>或者更准确点说，只要会引起 <code>modCount++</code>的操作，不通过迭代器进行都会出现一些问题。</p>
<p><strong>forEach</strong></p>
<p>我们先试试使用 <code>forEach()</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ArrayList&lt;String&gt; arrayList1 = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(<span class="string">&quot;A&quot;</span>,<span class="string">&quot;B&quot;</span>,<span class="string">&quot;C&quot;</span>,<span class="string">&quot;D&quot;</span>));</span><br><span class="line">arrayList1.forEach(arrayList1::remove); <span class="comment">// java.util.ConcurrentModificationException</span></span><br></pre></td></tr></table></figure>
<p>可见会抛出 <code>ConcurrentModificationException</code>异常，我们回到 <code>forEach()</code>的代码中：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">forEach</span><span class="params">(Consumer&lt;? <span class="keyword">super</span> E&gt; action)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取 modCount</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">    </span><br><span class="line">    ... ...</span><br><span class="line">    <span class="comment">// 每次循环都要检查并发修改</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; modCount == expectedModCount &amp;&amp; i &lt; size; i++) &#123;</span><br><span class="line">        action.accept(elementData[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    ... ...</span><br><span class="line">        </span><br><span class="line">    <span class="comment">// 遍历结束后才进行并发修改检测</span></span><br><span class="line">    <span class="keyword">if</span> (modCount != expectedModCount) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由于在方法执行的开始就令 <code>expectedModCount= modCount</code>，遍历过程中每次都要检查 <code>modCount == expectedModCount</code>，这样如果我们<strong>在匿名函数中对元素做了一些结构性操作，导致 <code>modCount</code>增加</strong>，就会在下一次循环判断的时候跳出循环，由于此时<code>modCount != expectedModCount</code>，所以会直接进入 if 分支抛出 <code>ConcurrentModificationException</code>异常。</p>
<p>我们可以验证一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">ArrayList&lt;String&gt; arrayList1 = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(<span class="string">&quot;A&quot;</span>,<span class="string">&quot;B&quot;</span>,<span class="string">&quot;C&quot;</span>));</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    list.forEach(s -&gt; &#123;</span><br><span class="line">        list.add(<span class="string">&quot;D&quot;</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125; <span class="keyword">catch</span> (ConcurrentModificationException e) &#123;</span><br><span class="line">    System.out.println(list); <span class="comment">// [A, B, C, D]</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>for循环</strong></p>
<p>由于 for 循环过程不像 <code>forEach()</code>那样在循环的结构中进行并发修改检测，因此结构性操作不会出现<code>ConcurrentModificationException</code>，但是<code>remove()</code>会漏删一下元素。我们来验证一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ArrayList&lt;String&gt; arrayList1 = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(<span class="string">&quot;A&quot;</span>,<span class="string">&quot;B&quot;</span>,<span class="string">&quot;C&quot;</span>,<span class="string">&quot;D&quot;</span>));</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; arrayList1.size(); i++) &#123;</span><br><span class="line">    arrayList1.remove(i);</span><br><span class="line">&#125;</span><br><span class="line">System.out.println(arrayList1); <span class="comment">// [B, D]</span></span><br></pre></td></tr></table></figure>
<p>可以看到，B 和 C 的删除被跳过了。实际上，这个问题和 AbstractList 的迭代器 Itr 中 <code>remove()</code> 方法遇到的问题有点像：</p>
<p>在 AbstractList 的 Itr 中，每次删除都会导致数组的“缩短”，在被删除元素的前一个元素会在 <code>remove()</code>后“补空”，落到被删除元素下标所对应的位置上，也就是说，<strong>假如有 a，b 两个元素，删除了下标为0的元素 a 以后，b 就会落到下标为0的位置</strong>。AbstractList 的 Itr 的解决方案是每次删除都把指向下一个的指针前移，那么 ArrayList 呢？</p>
<p>上文提到 ArrayList 的 <code>remove()</code> 调用了 <code>fastRemove()</code>方法，我们可以看看他是否就是罪魁祸首：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">fastRemove</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    ... ...</span><br><span class="line">    <span class="comment">// 如果不是在数组末尾删除</span></span><br><span class="line">    <span class="keyword">if</span> (numMoved &gt; <span class="number">0</span>)</span><br><span class="line">        <span class="comment">// 数组被缩短了</span></span><br><span class="line">        System.arraycopy(elementData, index+<span class="number">1</span>, elementData, index,</span><br><span class="line">                         numMoved);</span><br><span class="line">    elementData[--size] = <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可见<strong>数组“缩短”确实是导致的元素下标错位就是问题的根源</strong>，实际上，如果不是<code>i &lt; arrayList1.size()</code>在每次循环都会重新获取长度，那么早就抛异常了。</p>
<p>换句话说，如果不调用 <code>System.arraycopy()</code>方法，数组就不会“缩短”，理论上就不会引起这个问题，所以我们不妨试试反向删除：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ArrayList&lt;String&gt; arrayList1 = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(<span class="string">&quot;A&quot;</span>,<span class="string">&quot;B&quot;</span>,<span class="string">&quot;C&quot;</span>,<span class="string">&quot;D&quot;</span>));</span><br><span class="line"><span class="comment">// 反向删除</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = arrayList1.size() - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">    arrayList1.remove(i);</span><br><span class="line">&#125;</span><br><span class="line">System.out.println(arrayList1); <span class="comment">// []</span></span><br></pre></td></tr></table></figure>
<p>可见反向删除是没有问题的。</p>
<h2 id="八-其他">八、其他</h2>
<h3 id="1indexof-lastindexof-contains">1.indexOf / lastIndexOf / contains</h3>
<p>相比起 AbstractList ，ArrayList 不再使用迭代器，而是改写成了根据下标进行for循环：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// indexOf</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">indexOf</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (o == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; size; i++)</span><br><span class="line">            <span class="keyword">if</span> (elementData[i]==<span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">return</span> i;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; size; i++)</span><br><span class="line">            <span class="keyword">if</span> (o.equals(elementData[i]))</span><br><span class="line">                <span class="keyword">return</span> i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// lastIndexOf</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">lastIndexOf</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (o == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = size-<span class="number">1</span>; i &gt;= <span class="number">0</span>; i--)</span><br><span class="line">            <span class="keyword">if</span> (elementData[i]==<span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">return</span> i;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = size-<span class="number">1</span>; i &gt;= <span class="number">0</span>; i--)</span><br><span class="line">            <span class="keyword">if</span> (o.equals(elementData[i]))</span><br><span class="line">                <span class="keyword">return</span> i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>至于 <code>contains()</code> 方法，由于已经实现了 <code>indexOf()</code>，自然不必继续使用 AbstractCollection 提供的迭代查找了，而是改成了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">contains</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> indexOf(o) &gt;= <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2sublist">2.subList</h3>
<p><code>subList()</code> 和 <code>iterator()</code>一样，也是返回一个特殊的内部类 SubList，在 AbstractList 中也已经有相同的实现，只不过在 ArrayList 里面进行了一些改进，大体逻辑和 AbstractList 中是相似的，这部分内容在前文已经有提到过，这里就不再多费笔墨。</p>
<h3 id="3sort">3.sort</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(Comparator&lt;? <span class="keyword">super</span> E&gt; c)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">    Arrays.sort((E[]) elementData, <span class="number">0</span>, size, c);</span><br><span class="line">    <span class="keyword">if</span> (modCount != expectedModCount) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">    modCount++;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>java 中集合排序要么元素类实现 Comparable 接口，要么自己写一个 Comparator 比较器。这个函数的参数指明了类型是比较器，因此只能传递自定义的比较器，在 JDK8 以后，Comparator 类提供的了一些默认实现，我们可以以类似 <code>Comparator.reverseOrder()</code> 的方式去调用，或者直接用 lambda 表达式传入一个匿名方法。</p>
<h3 id="4toarray">4.toArray</h3>
<p><code>toArray()</code> 方法在 AbstractList 的父类 AbstractCollection 中已经有过基本的实现，ArrayList 根据自己的情况重写了该方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> Object[] toArray() &#123;</span><br><span class="line">    <span class="comment">// 直接返回 elementData 的拷贝</span></span><br><span class="line">    <span class="keyword">return</span> Arrays.copyOf(elementData, size);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> &lt;T&gt; T[] toArray(T[] a) &#123;</span><br><span class="line">    <span class="comment">// 如果传入的素组比本集合的元素数量少</span></span><br><span class="line">    <span class="keyword">if</span> (a.length &lt; size)</span><br><span class="line">        <span class="comment">// 直接返回elementData的拷贝</span></span><br><span class="line">        <span class="keyword">return</span> (T[]) Arrays.copyOf(elementData, size, a.getClass());</span><br><span class="line">    <span class="comment">// 把elementData的0到size的元素覆盖到传入数组</span></span><br><span class="line">    System.arraycopy(elementData, <span class="number">0</span>, a, <span class="number">0</span>, size);</span><br><span class="line">    <span class="comment">// 如果传入数组元素比本集合的元素多</span></span><br><span class="line">    <span class="keyword">if</span> (a.length &gt; size)</span><br><span class="line">        <span class="comment">// 让传入数组size位置变为null</span></span><br><span class="line">        a[size] = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">return</span> a;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="5clone">5.clone</h3>
<p>ArrayList 实现了 Cloneable 接口，因此他理当有自己的 <code>clone()</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">clone</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// Object.clone()拷贝ArrayList</span></span><br><span class="line">        ArrayList&lt;?&gt; v = (ArrayList&lt;?&gt;) <span class="keyword">super</span>.clone();</span><br><span class="line">        <span class="comment">// 拷贝</span></span><br><span class="line">        v.elementData = Arrays.copyOf(elementData, size);</span><br><span class="line">        v.modCount = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">return</span> v;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (CloneNotSupportedException e) &#123;</span><br><span class="line">        <span class="comment">// this shouldn&#x27;t happen, since we are Cloneable</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> InternalError(e);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>要注意的是， <code>Object.clone()</code>是浅拷贝， <code>Arrays.copyOf()</code>也是浅拷贝，因此我们拷贝出来的 ArrayList 不同，内部的 elementData 不同，但是 elementData 中的数据，也就是容器中的数据还是相同的。我们举个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">    ArrayList&lt;MyBean&gt; arrayList1 = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(<span class="keyword">new</span> MyBean()));</span><br><span class="line">    ArrayList&lt;MyBean&gt; arrayList2 = (ArrayList&lt;MyBean&gt;) arrayList1.clone();</span><br><span class="line">    System.out.println(arrayList1); <span class="comment">// [$MyBean@782830e]</span></span><br><span class="line">    System.out.println(arrayList2); <span class="comment">// [$MyBean@782830e]</span></span><br><span class="line">    System.out.println(arrayList1 == arrayList2); <span class="comment">// false</span></span><br><span class="line"></span><br><span class="line">    arrayList1.add(<span class="keyword">new</span> MyBean());</span><br><span class="line">    System.out.println(arrayList1); <span class="comment">// [MyBean@782830e, $MyBean@470e2030]</span></span><br><span class="line">    arrayList2.add(<span class="keyword">new</span> MyBean());</span><br><span class="line">    System.out.println(arrayList2); <span class="comment">// [$MyBean@782830e, $MyBean@3fb4f649]</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBean</span> </span>&#123;&#125;</span><br></pre></td></tr></table></figure>
<h3 id="6isempty">6.isEmpty</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isEmpty</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> size == <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="九-总结">九、总结</h2>
<p><strong>数据结构</strong></p>
<p>ArrayList 底层是 Object[] 数组，被 RandomAccess 接口标记，具有根据下标高速随机访问的功能；</p>
<p><strong>扩容缩容</strong></p>
<p>ArrayList 扩容是扩大1.5倍，只有构造方法指定初始容量为0时，才会在第一次扩容出现小于10的容量，否则第一次扩容后的容量必然大于等于10；</p>
<p>ArrayList 有缩容方法<code>trimToSize()</code>，但是自身不会主动调用。当调用后，容量会缩回实际元素数量，最小会缩容至默认容量10；</p>
<p>ArrayList 的添加可能会因为扩容导致数组“膨胀”，同理，不是所有的删除都会引起数组“缩水”：当删除的元素是队尾元素，或者<code>clear()</code>方法都只会把下标对应的地方设置为null，而不会真正的删除数组这个位置；</p>
<p><strong>迭代中的操作</strong></p>
<p>ArrayList 在循环中删除——准确的讲，是任何会引起 <code>modCount</code>变化的结构性操作——可能会引起意外：</p>
<ul>
<li><p>在 <code>forEach()</code>删除元素会抛<code>ConcurrentModificationException</code>异常，因为 <code>forEach()</code>在循环开始前就获取了 <code>modCount</code>，每次循环都会比较旧 <code>modCount</code>和最新的 <code>modCount</code>，如果循环进行了会使<code>modCount</code>变动的操作，就会在下一次循环开始前抛异常；</p></li>
<li><p>在 for 循环里删除实际上是以步长为2对节点进行删除，因为删除时数组“缩水”导致原本要删除的下一下标对应的节点，却落到了当前被删除的节点对应的下标位置，导致被跳过。</p>
<p>如果从队尾反向删除，就不会引起数组“缩水”，因此是正常的。</p></li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/java%E9%9B%86%E5%90%88%E5%AE%B9%E5%99%A8/" rel="tag"># java集合容器</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/11/27/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9AList%E4%B8%8EAbstractList/" rel="next" title="java集合源码分析（二）：List与AbstractList">
                <i class="fa fa-chevron-left"></i> java集合源码分析（二）：List与AbstractList
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/12/03/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E5%9B%9B%EF%BC%89%EF%BC%9ALinkedList/" rel="prev" title="java集合源码分析（四）：LinkedList">
                java集合源码分析（四）：LinkedList <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-arraylist-%E7%9A%84%E7%B1%BB%E5%85%B3%E7%B3%BB"><span class="nav-text">一、ArrayList 的类关系</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1abstractlist-%E4%B8%8E-list"><span class="nav-text">1.AbstractList 与 List</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2randomaccess"><span class="nav-text">2.RandomAccess</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3cloneable"><span class="nav-text">3.Cloneable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4serializable"><span class="nav-text">4.Serializable</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-%E6%88%90%E5%91%98%E5%8F%98%E9%87%8F"><span class="nav-text">二、成员变量</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1serialversionuid"><span class="nav-text">1.serialVersionUID</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2default_capacity"><span class="nav-text">2.DEFAULT_CAPACITY</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3empty_elementdata"><span class="nav-text">3.EMPTY_ELEMENTDATA</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4defaultcapacity_empty_elementdata"><span class="nav-text">4.DEFAULTCAPACITY_EMPTY_ELEMENTDATA</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5elementdata"><span class="nav-text">5.elementData</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6size"><span class="nav-text">6.size</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7max_array_size"><span class="nav-text">7.MAX_ARRAY_SIZE</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="nav-text">三、构造方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B-%E6%89%A9%E5%AE%B9%E7%BC%A9%E5%AE%B9"><span class="nav-text">四、扩容缩容</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#0systemarraycopy"><span class="nav-text">0.System.arraycopy()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E6%89%A9%E5%AE%B9"><span class="nav-text">1.扩容</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E7%BC%A9%E5%AE%B9"><span class="nav-text">2.缩容</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E6%B5%8B%E8%AF%95"><span class="nav-text">3.测试</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%94-%E6%B7%BB%E5%8A%A0-%E8%8E%B7%E5%8F%96"><span class="nav-text">五、添加 &#x2F; 获取</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1add"><span class="nav-text">1.add</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2addall"><span class="nav-text">2.addAll</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3get"><span class="nav-text">3.get</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AD-%E5%88%A0%E9%99%A4-%E4%BF%AE%E6%94%B9"><span class="nav-text">六、删除 &#x2F; 修改</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1remove"><span class="nav-text">1.remove</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2clear"><span class="nav-text">2.clear</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3removeall-retainall"><span class="nav-text">3.removeAll &#x2F; retainAll</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4removeif"><span class="nav-text">4.removeIf</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5set"><span class="nav-text">5.set</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6replaceall"><span class="nav-text">6.replaceAll</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%83-%E8%BF%AD%E4%BB%A3"><span class="nav-text">七、迭代</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1iterator-listiterator"><span class="nav-text">1.iterator &#x2F; listIterator</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2foreach"><span class="nav-text">2.forEach</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E8%BF%AD%E4%BB%A3%E5%88%A0%E9%99%A4%E5%AD%98%E5%9C%A8%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-text">3.迭代删除存在的问题</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AB-%E5%85%B6%E4%BB%96"><span class="nav-text">八、其他</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1indexof-lastindexof-contains"><span class="nav-text">1.indexOf &#x2F; lastIndexOf &#x2F; contains</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2sublist"><span class="nav-text">2.subList</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3sort"><span class="nav-text">3.sort</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4toarray"><span class="nav-text">4.toArray</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5clone"><span class="nav-text">5.clone</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6isempty"><span class="nav-text">6.isEmpty</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B9%9D-%E6%80%BB%E7%BB%93"><span class="nav-text">九、总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
